package com.csf.controller;

import com.alibaba.fastjson.JSONObject;
import com.csf.entity.Message;
import com.csf.entity.Page;
import com.csf.entity.SessionReplace;
import com.csf.entity.User;
import com.csf.service.MessageService;
import com.csf.service.UserService;
import com.csf.util.CommunityActivation;
import com.csf.util.communityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
public class MessageController implements CommunityActivation {

    @Autowired
    private SessionReplace sessionReplace;

    @Autowired
    private UserService userService;

    @Autowired
    private MessageService messageService;

    @RequestMapping(path = "/letter",method = RequestMethod.GET)
    public String letterDetail(Model model, Page page){
        //        获取当前登录用户
        User user = sessionReplace.getUser();

//        开始设置分页
        page.setPath("/letter");
        page.setLimit(5);
//        获取页数
        page.setRows(messageService.conversationCount(user.getId()));


        //获取与当前用户所有的会话
        List<Message> conversations = messageService.findConversations(user.getId(), page.getiniRows(), page.getLimit());
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (Message conversation : conversations) {
            Map<String,Object> map = new HashMap<>();
            if (conversation != null){
                map.put("conversation",conversation);
//                获取当前与之私信的人共有几条消息
                map.put("letterCount",messageService.userletterCount(conversation.getConversationId()));
//                获取当前用户与私信的人中未读数量
                map.put("letterUserUnread",messageService.userLetterUnRead(user.getId(), conversation.getConversationId()));
//                获取私信对象的所有信息
                int target = user.getId() == conversation.getFromId() ? conversation.getToId() : conversation.getFromId();
                User targetUser = userService.findUserById(target);
                map.put("targetUser",targetUser);
            }
            mapList.add(map);
        }
        model.addAttribute("mapList",mapList);
        //                获取当前未读的所有数据
        model.addAttribute("letterUnread",messageService.userLetterUnRead(user.getId(), null));
//        获取系统通知未读的总数
        int messageUnReadCount = messageService.findUnReadCount(user.getId(), null);
        model.addAttribute("messageUnReadCount",messageUnReadCount);
        return "site/letter";
    }

    @RequestMapping(path = "/letterdetail/{conversationId}",method = RequestMethod.GET)
    public String getMessageDetail(@PathVariable("conversationId")String conversationId,Page page,Model model){

        //设置分页
        page.setLimit(5);
        page.setPath("/letterdetail/"+conversationId);
        page.setRows(messageService.userletterCount(conversationId));

        //获取当前会话ID所有的私信信息
        List<Message> userLetters = messageService.findUserLetters(conversationId, page.getiniRows(), page.getLimit());
        List<Map<String,Object>> maps = new ArrayList<>();
        if (userLetters != null){
            for (Message letter : userLetters) {
                Map<String,Object> map = new HashMap<>();
                map.put("letter",letter);
//                每条私信是谁发的
                map.put("fromUser",userService.findUserById(letter.getFromId()));
                maps.add(map);
            }
            model.addAttribute("maps",maps);
        }

        List<Integer> unreadLetter = getTargetUnreadLetter(userLetters);
        if (!unreadLetter.isEmpty()) {
            messageService.updateLetterStatus(unreadLetter, 1);
        }
        model.addAttribute("letterTarget",getLetterTarget(conversationId));
        return "/site/letter-detail";
    }
//    获取未读的单人私信
    private List<Integer> getTargetUnreadLetter(List<Message> userLetters){
        List<Integer> integerList = new ArrayList<>();
        if (userLetters != null){
            for (Message userLetter : userLetters) {
//                进行判断，如果当前登录人员的id与发送对象id匹配并且消息状态为0
                if (sessionReplace.getUser().getId() == userLetter.getToId() && userLetter.getStatus() ==0){
                        integerList.add(userLetter.getId());
                }
            }
        }
        return integerList;
    }


    public User getLetterTarget(String conversationId){

        String[] split = conversationId.split("_");
        int id1 = Integer.parseInt(split[0]);
        int id2 = Integer.parseInt(split[1]);

        if (sessionReplace.getUser().getId()==id1){
            return userService.findUserById(id2);
        }else{
            return userService.findUserById(id1);
        }
    }

    @RequestMapping(value = "insertMessage",method = RequestMethod.POST)
    @ResponseBody
    public String addMessage(String toName,String toContent){
        User targetName = userService.findUserByUsername(toName);
        if (targetName == null){
            return communityUtils.getJsonString(1,"该用户不存在");
        }
        Message message = new Message();
        message.setContent(toContent);
//        从哪里发出去
        message.setFromId(sessionReplace.getUser().getId());
//        发到哪里去
        message.setToId(targetName.getId());
        if (message.getFromId() > message.getToId()){
            message.setConversationId(message.getToId()+"_"+ message.getFromId());
        }else {
            message.setConversationId(message.getFromId()+"_"+ message.getToId());
        }
        message.setCreateTime(new Date());

        messageService.insertMessage(message);
        return communityUtils.getJsonString(0);
    }

    /**
     * 获取系统消息部分
     */
    @RequestMapping(path = "/notice/list",method = RequestMethod.GET)
    public String getSystemMessage(Model model){
//        获取当前登录用户
        User localUser = sessionReplace.getUser();
        /**
         * 处理评论通知
         */
        Message lastMessage = messageService.findLastMessage(localUser.getId(), TOPIC_COMMENT);
        System.out.println("lastMessage是:"+lastMessage);

        if (lastMessage != null){
            Map<String,Object> messageVo = new HashMap<>();
            messageVo.put("lastMessage",lastMessage);
//          因为content为json格式的字符串，而且中间还有特殊字符，我们需要对其进行处理
            String htmlUnescape = HtmlUtils.htmlUnescape(lastMessage.getContent());
            Map<String,Object> content = JSONObject.parseObject(htmlUnescape,HashMap.class);
            messageVo.put("user",userService.findUserById((Integer) content.get("userId")));
            messageVo.put("entityType",content.get("entityType"));
            messageVo.put("entityId",content.get("entityId"));
            messageVo.put("postId",content.get("postId"));
//          获取评论通知的未读消息
            int unReadCount = messageService.findUnReadCount(localUser.getId(), TOPIC_COMMENT);
            messageVo.put("unReadCount",unReadCount);
//          获取评论通知的所有消息
            messageVo.put("messageTotal",messageService.findMessageTotal(localUser.getId(), TOPIC_COMMENT));
            model.addAttribute("commentMessage",messageVo);
        }

        /**
         * 处理点赞通知
         */
        lastMessage = messageService.findLastMessage(localUser.getId(),TOPIC_LIKE);

        if (lastMessage != null){
            Map<String,Object> messageVo = new HashMap<>();
            messageVo.put("lastMessage",lastMessage);
            //因为content为json格式的字符串，而且中间还有特殊字符，我们需要对其进行处理
            String htmlUnescape = HtmlUtils.htmlUnescape(lastMessage.getContent());
            Map<String,Object> content = JSONObject.parseObject(htmlUnescape,HashMap.class);
            messageVo.put("user",userService.findUserById((Integer) content.get("userId")));
            messageVo.put("entityType",content.get("entityType"));
            messageVo.put("entityId",content.get("entityId"));
            messageVo.put("postId",content.get("postId"));
            //获取评论通知的未读消息
            int unReadCount = messageService.findUnReadCount(localUser.getId(), TOPIC_LIKE);
            messageVo.put("unReadCount",unReadCount);
            //获取评论通知的所有消息
            messageVo.put("messageTotal",messageService.findMessageTotal(localUser.getId(), TOPIC_LIKE));
            model.addAttribute("likeMessage",messageVo);
        }

        //获取系统通知未读的总数
        int messageUnReadCount = messageService.findUnReadCount(localUser.getId(), null);
        model.addAttribute("messageUnReadCount",messageUnReadCount);
        //获取当前未读的所有数据
        model.addAttribute("letterUnread",messageService.userLetterUnRead(localUser.getId(), null));
        return "site/notice";
    }

    @RequestMapping(path = "/notice/detail/{topic}",method = RequestMethod.GET)
    public String getNoticeList(@PathVariable("topic") String topic,Page page,Model model){
//        当前登录用户
        User localUser = sessionReplace.getUser();
//        分页设置
        page.setLimit(5);
        page.setRows(messageService.findMessageTotal(localUser.getId(), topic));
        page.setPath("/notice/detail/"+topic);
//        获取该主题下的所有通知列表
        List<Message> messages = messageService.findMessageList(localUser.getId(), topic, page.getiniRows(), page.getLimit());
        List<Map<String,Object>> mapList = new ArrayList<>();
        if (messages != null) {
            for (Message message : messages) {
                Map<String, Object> map = new HashMap<>();
                map.put("message", message);
//                获取内容
                String htmlUnescape = HtmlUtils.htmlUnescape(message.getContent());
                Map<String,Object> content = JSONObject.parseObject(htmlUnescape,HashMap.class);
//
                map.put("entityType",content.get("entityType"));
                map.put("entityId",content.get("entityId"));
                map.put("postId",content.get("postId"));
                map.put("user",userService.findUserById((Integer) content.get("userId")));
                //系统信息
                map.put("systemUser",userService.findUserById(message.getFromId()));
                mapList.add(map);
            }
            model.addAttribute("notices",mapList);
        }
//        改变消息状态
        List<Integer> ids = getTargetUnreadLetter(messages);
        for (int i:ids){
            messageService.updateStatus(i,1);
        }
        return "site/notice-detail";
    }
}
